<?php
/**
 * Created by PhpStorm.
 * User: 异步加载
 * Date: 2017/12/23
 * Time: 11:29
 */

namespace app\api\service;


use app\lib\enum\ScopeEnum;
use app\lib\exception\ForbiddenException;
use app\lib\exception\TokenException;
use think\Cache;
use think\Exception;
use think\Request;

class Token
{
    /**
     * @return string
     * 生成随机MD5加密字符串
     */
    public static function generateToken(){
        //32个字符生成随机字符串
        $randchars = getRandChar(32);
        //用三组字符串MD5加密
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        //salt 盐
        $salt = config('secure.token_salt');
        return md5($randchars.$timestamp.$salt);
    }

    /**
     * @param $key
     * @return mixed
     * @throws Exception
     * @throws TokenException
     * 根据客户端传来的uid从缓存中读取Token
     */
    public static function getCurrentTokenVar($key){
        $token = Request::instance()
            ->header('token');
        $vars = Cache::get($token);
        if(!$vars){
            throw new TokenException();
        }else{
            if(!is_array($vars)){
                $vars = json_decode($vars,true);
            }
            if(array_key_exists($key,$vars)){
                return $vars[$key];
            }else{
                throw new Exception('尝试获取的Token变量并不存在');
            }
        }
    }

    /**
     * @return mixed
     * 获取uid
     */
    public static function getCurrentUid(){
        $uid = self::getCurrentTokenVar('uid');
        return $uid;
    }

    /**
     * @return bool
     * @throws ForbiddenException
     * @throws TokenException
     * 权限检查 需要大于大于用户权限
     */
    public static function needPrimaryScope(){
        $scope = self::getCurrentTokenVar('scope');
        if($scope){
            if($scope >= ScopeEnum::User){
                return true;
            }else{
                throw new ForbiddenException();
            }
        }else{
            throw new TokenException();
        }
    }

    /**
     * @return bool
     * @throws ForbiddenException
     * @throws TokenException
     * 权限检查 只有用户才能访问
     */
    public static function needExclusiveScope(){
        $scope = self::getCurrentTokenVar('scope');
        if($scope){
            if($scope == ScopeEnum::User){
                return true;
            }else{
                throw new ForbiddenException();
            }
        }else{
            throw new TokenException();
        }
    }
}